package william.list;

/**
 * @author ZhangShenao
 * @date 2024/3/12
 * @description <a href="https://leetcode.cn/problems/swap-nodes-in-pairs/description/">...</a>
 */
public class Leetcode24_两两交换链表中的节点 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    /**
     * 借助哑头节点实现
     * 从哑头节点开始,遍历链表,找到后面的两个节点,进行交换
     * <p>
     * 时间复杂度O(N) 需要遍历一次链表
     * 空间复杂度O1()
     */
    public ListNode swapPairs(ListNode head) {
        //边界条件校验
        if (head == null) {
            return head;
        }

        //借助哑头节点
        ListNode dummy = new ListNode();
        dummy.next = head;

        //从哑头节点开始,遍历链表,找到后面的两个节点,进行交换
        ListNode pre = dummy;
        while (pre.next != null && pre.next.next != null) {
            //交换节点
            ListNode first = pre.next;
            ListNode second = first.next;
            ListNode next = second.next;

            second.next = first;
            first.next = next;
            pre.next = second;

            //找到下一对节点的前继节点,继续遍历
            pre = first;
        }

        //返回头节点
        return dummy.next;
    }
}
